package com.gzu.ltms.consumer;

import cn.hutool.core.util.RandomUtil;
import com.gzu.ltms.constant.RedisKeyConstants;
import com.gzu.ltms.entity.vo.SendVerificationCodeReqVO;
import com.gzu.ltms.sms.AliyunSmsHelper;
import com.gzu.ltms.uitl.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
@RocketMQMessageListener(consumerGroup = "ltms_group",
        topic = "send",
        consumeMode = ConsumeMode.ORDERLY)
@Slf4j
public class SendConsumer implements RocketMQListener<Message> {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;


    @Override
    public void onMessage(Message message) {
        // 消息体
        String bodyJson = new String(message.getBody());
        // 标签
        String tags = message.getTags();
        log.info("==> 消费了消息: {}, tags:{}", bodyJson, tags);


        // 将消息体转为 SendVerificationCodeReqVO 对象
        SendVerificationCodeReqVO sendVerificationCodeReqVO = JsonUtils.parseObject(bodyJson, SendVerificationCodeReqVO.class);
        if (Objects.isNull(sendVerificationCodeReqVO)) return;
        // 手机号
        String phone = sendVerificationCodeReqVO.getPhone();
        // 构建验证码 redis key
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);

        // 生成 6 位随机数字验证码
        String verificationCode = RandomUtil.randomNumbers(6);

        log.info("==> 手机号: {}, 已生成验证码：【{}】", phone, verificationCode);

        // todo: 调用第三方短信发送服务
        String signName = "阿里云短信测试";
        String templateCode = "SMS_154950909";
        String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
        aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);


        // 存储验证码到 redis, 并设置过期时间为 3 分钟
        redisTemplate.opsForValue().set(key, verificationCode, 3, TimeUnit.MINUTES);

    }
}
